
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/if_ether.h>
#include <netinet/ether.h>
#include <ctype.h>
#include "get_mac.h"

static char *
ether_ntoa_r_self (const struct ether_addr *addr, char *buf)
{
  	sprintf (buf, "%02x%02x%02x%02x%02x%02x",
  	   	addr->ether_addr_octet[0], addr->ether_addr_octet[1],
  	   	addr->ether_addr_octet[2], addr->ether_addr_octet[3],
	   	addr->ether_addr_octet[4], addr->ether_addr_octet[5]);
     	return buf;
}

static char *
ether_ntoa_self (const struct ether_addr *addr)
{
  	static char asc[18];
   	return ether_ntoa_r_self (addr, asc);
}

char * get_eth_mac(char * EthNumberString)
{
        int sockfd = 0;
	unsigned char mac[MAC_LEN] = {0};
        struct ifreq struReq;
	
	memset(&struReq, 0 ,sizeof(struct ifreq));
	
        if ( -1 == (sockfd = socket(PF_INET,SOCK_STREAM,0)))
	{
		//printf("Error in socket function.\n");
		//fprintf(stderr, "%d-%s\n", __LINE__, strerror(errno));
	}
	
        strncpy(struReq.ifr_name, EthNumberString, sizeof(struReq.ifr_name));
        
	if ( 0 != ioctl(sockfd,SIOCGIFHWADDR,&struReq))
	{
		//printf("Error in ioctl function.\n");
		//fprintf(stderr, "%d-%s\n", __LINE__, strerror(errno));
	}
	memcpy(mac, struReq.ifr_hwaddr.sa_data, MAC_LEN);
	close(sockfd);

	return ether_ntoa_self((struct ether_addr *) mac);
}

static char *get_name(char *name, char *p)
{
    	while (isspace(*p))
		p++;
    	while (*p) {
		if (isspace(*p))
	    		break;
		if (*p == ':') {	/* could be an alias */
	    		char *dot = p, *dotname = name;
	    		*name++ = *p++;
			while (isdigit(*p))
				*name++ = *p++;
			if (*p != ':') {	/* it wasn't, backup */
				p = dot;
				name = dotname;
			}
			if (*p == '\0')
				return NULL;
			p++;
			break;
		}
	*name++ = *p++;
    	}
    	*name++ = '\0';
    	return p;
}

int get_all_eth_mac(char * ret_buffer)
{
    	FILE *fh;
    	char buf[512];
    	int err;

    	fh = fopen(_PATH_PROCNET_DEV, "r");
    	if (!fh) {
		//fprintf(stderr, "Warning: cannot open %s (%s). Limited output.\n",
		//	_PATH_PROCNET_DEV, strerror(errno)); 
	}	
    	fgets(buf, sizeof buf, fh);	/* eat line */
    	fgets(buf, sizeof buf, fh);

    	err = 0;
    	while (fgets(buf, sizeof buf, fh)) {
		char name[IFNAMSIZ];
		get_name(name, buf);
		if (!strncmp("eth",name, 3)) {
			strcat (ret_buffer, get_eth_mac(name));
			//printf("dev name:%s\n",name);
		}	
    	}
    	if (ferror(fh)) {
		perror(_PATH_PROCNET_DEV);
		err = -1;
    	}

    	fclose(fh);
    	return err;
}

/*
int main()
{
	printf("Mac:%s\n", get_eth_mac(DEV_ETH_NUMBER));
	return 0;
}
*/


